package com.site.service.impl.backend.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.site.dao.backend.system.AuthDao;
import com.site.dao.backend.system.RoleDao;
import com.site.dto.backend.system.AuthorityBizBean;
import com.site.dto.backend.system.ResourseBizBean;
import com.site.dto.backend.system.RoleBizBean;
import com.site.dto.backend.system.UsersBizBean;
import com.site.model.backend.system.AuthorityInfo;
import com.site.model.backend.system.ResourseInfo;
import com.site.model.backend.system.RoleInfo;
import com.site.model.backend.system.UsersInfo;
import com.site.service.backend.system.RoleService;
import com.site.util.PropertyUtils;
import com.site.util.StringUtils;
import com.site.util.base.service.BaseService;
import com.site.util.base.service.BaseServiceImpl;
import com.site.util.exception.ApplicationException;
import com.site.util.exception.SystemException;
import com.site.util.extremetable.QueryPage;

/**
 * 角色Service
 * @author Lee 2012-12-04 
 *
 */
@Component("roleService")
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

 
	private RoleDao roleDao;
	
	private AuthDao authDao;
	
	public RoleDao getRoleDao() {
		return roleDao;
	}
	@Resource
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Override
	public List<RoleBizBean> getRoleList(QueryPage queryPage, RoleBizBean vo) {
		List<RoleInfo> roleInfoList = roleDao.getRoleList(queryPage, vo);
		List<RoleBizBean> roleBizBeanList = new ArrayList<RoleBizBean>();
		if(null != roleInfoList && roleInfoList.size() > 0){
			for (RoleInfo roleInfo : roleInfoList) {
				if(null != roleInfo){
					RoleBizBean roleBizBean = new RoleBizBean();
					// 角色
					PropertyUtils.copyProperties(roleBizBean, roleInfo);
					// 权限
					if(null != roleInfo.getAuthoritySet() && roleInfo.getAuthoritySet().size() > 0){
						Set<AuthorityBizBean> authVOSet = getCopyAuth(roleInfo.getAuthoritySet());
						roleBizBean.setAuthoritySet(authVOSet);
					}
					// 用户
					if(null != roleInfo.getUserSet() && roleInfo.getUserSet().size() > 0){
						Set<UsersBizBean> usersVOSet = getCopyUsers(roleInfo.getUserSet());
						roleBizBean.setUserSet(usersVOSet);
					}
					roleBizBeanList.add(roleBizBean);
				}
			}
		}
		return roleBizBeanList;
	}
	
	/**
	 * copy 权限
	 * @param authSet
	 * @return
	 */
	private Set<AuthorityBizBean> getCopyAuth(Set<AuthorityInfo> authSet) {
		Set<AuthorityBizBean> authVoSet = new HashSet<AuthorityBizBean>();
		if (authSet != null && authSet.size() > 0) {
			for (Iterator<AuthorityInfo> iterator = authSet.iterator(); iterator.hasNext();) {
				AuthorityInfo authPO = iterator.next();
				AuthorityBizBean authVO = new AuthorityBizBean();
				PropertyUtils.copyProperties(authVO, authPO);
				authVoSet.add(authVO);
			}
		}
		return authVoSet;
	}
	
	/**
	 * copy 用户
	 * @param authSet
	 * @return
	 */
	private Set<UsersBizBean> getCopyUsers(Set<UsersInfo> userSet) {
		Set<UsersBizBean> usersVoSet = new HashSet<UsersBizBean>();
		if (userSet != null && userSet.size() > 0) {
			for (Iterator<UsersInfo> iterator = userSet.iterator(); iterator.hasNext();) {
				UsersInfo usersPO = iterator.next();
				UsersBizBean usersVO = new UsersBizBean();
				PropertyUtils.copyProperties(usersVO, usersPO);
				usersVoSet.add(usersVO);
			}
		}
		return usersVoSet;
	}

	@Override
	public Object doExecute(Object obj, String command) throws SystemException,
			ApplicationException {
		if(command.equals(BaseService.COMMAND_SAVE)){
			save((RoleBizBean)obj);
		} else if(command.equals(BaseService.COMMAND_UPDATE)){
			update((RoleBizBean)obj);
		} else if(command.equals("disabled")){
			disabled((String)obj);
		} else if(command.equals("saveRoleUser")){
			saveRoleUser((RoleBizBean)obj);
		} else if(command.equals("deleteRoleUser")){
			deleteRoleUser((RoleBizBean)obj);	
		} else if(command.equals("enabled")){
			enabled((String)obj);
		} else if(command.equals("saveRoleAuth")){
			saveRoleAuth((RoleBizBean)obj);
		} else if(command.equals("deleteRoleAuth")){
			deleteRoleAuth((RoleBizBean)obj);
		} else if(command.equals("saveRoleMenu")){
			saveRoleMenu((RoleBizBean)obj);
		} else if(command.equals("deleteRoleMenu")){
			deleteRoleMenu((RoleBizBean)obj);
		} else if(COMMAND_DELETE.equals(command)){
			// 物理删除
			return roleDelete((List<RoleBizBean>)obj);
		}
		return null;
	}
	
	/**
	 * 禁用角色
	 * @param obj
	 */
	private void disabled(String obj) {
		if(null != obj && obj.length() > 0){
			List<Long> ids = StringUtils.splitToListByLong(obj);
			for (Long long1 : ids) {
				roleDao.disabled(long1);
			}
		}
	}
	/**
	 * 物理删除
	 * @param obj
	 * @return
	 */
	private String roleDelete(List<RoleBizBean> obj) {
		StringBuffer sb = new StringBuffer();
		for (RoleBizBean long1 : obj) {
			RoleInfo po = null;
			try {
				if(null != long1 && null != long1.getId()){
					po = roleDao.getEntityById(RoleInfo.class, long1.getId());
					roleDao.delete(RoleInfo.class, long1.getId());
					if(null != po){
						sb.append(po.getRoleName());
						sb.append(";");
					}
				}
			} catch (Exception e) {
				log.info(e.getMessage());
				if(null != po){
					sb.append(po.getRoleName());
					sb.append(";");
				}
			}
		}
		
		if(!StringUtils.isEmpty(sb.toString())){
			log.debug(sb.toString());
			return StringUtils.removeLastComma2(sb.toString());
		}
		
		return null;
	}
	/**
	 * 删除角色资源
	 * @param obj
	 */
	private void deleteRoleMenu(RoleBizBean obj) {
		if(null != obj){
			roleDao.deleteRoleMenu(obj);
		} else {
			log.info("删除角色资源错误！");
			throw new ApplicationException("删除角色资源错误！");
		}
	}
	/**
	 * 增加角色资源
	 * @param obj
	 */
	private void saveRoleMenu(RoleBizBean obj) {
		if(null != obj){
			roleDao.saveRoleMenu(obj);
		} else {
			log.info("保存角色资源错误！");
			throw new ApplicationException("保存角色资源错误！");
		}
	}
	/**
	 * 删除角色权限
	 * @param obj
	 */
	private void deleteRoleAuth(RoleBizBean obj) {
		if(null != obj){
			roleDao.deleteRoleAuth(obj);
		} else {
			log.info("删除角色权限错误！");
			throw new ApplicationException("删除角色权限错误！");
		}
	}
	/**
	 * 保存角色权限
	 * @param obj
	 */
	private void saveRoleAuth(RoleBizBean obj) {
		if(null != obj){
			roleDao.saveRoleAuth(obj);
		} else {
			log.info("保存角色权限错误！");
			throw new ApplicationException("保存角色用户错误！");
		}
	}
	/**
	 * 启用角色用户
	 * @param obj
	 */
	private void enabled(String obj) {
		if(null != obj && obj.length() > 0){
			List<Long> ids = StringUtils.splitToListByLong(obj);
			for (Long long1 : ids) {
				roleDao.enabled(long1);
			}
		}
	}
	/**
	 * 删除角色用户
	 * @param obj
	 */
	private void deleteRoleUser(RoleBizBean obj) {
		if(null != obj){
			roleDao.deleteRoleUser(obj);
		} else {
			log.info("删除角色用户错误！");
			throw new ApplicationException("删除角色用户错误！");
		}
	}
	/**
	 * 保存角色用户
	 * @param obj
	 */
	private void saveRoleUser(RoleBizBean obj) {
		if(null != obj){
			roleDao.saveRoleUser(obj);
		} else {
			log.info("保存角色用户错误！");
			throw new ApplicationException("保存角色用户错误！");
		}
	}
	
	/**
	 * 更新角色
	 * @param roleBizBean
	 */
	private void update(RoleBizBean roleBizBean) {
		if(null != roleBizBean){
			roleDao.update(roleBizBean);
		} else {
			log.info("角色对象为空了,不能执行更新操作!");
		}
	}
	/**
	 * 保存角色
	 * @param obj
	 */
	private void save(RoleBizBean obj) {
		if(null != obj){
			roleDao.save(obj);
		} else {
			log.info("角色Id为空了,不能执行保存操作!");
		}
	}
	@Override
	public List<UsersBizBean> getRoleUsers(Long roleId) {
		
		List<UsersInfo> usersInfoList = roleDao.getRoleUsers(roleId);
		List<UsersBizBean> usersList = new ArrayList<UsersBizBean>();
		
		if(null != usersInfoList && usersInfoList.size() > 0){
			UsersBizBean usersBizBean = null;
			for (UsersInfo usersInfo : usersInfoList) {
				if(null != usersInfo){
					usersBizBean = new UsersBizBean();
					PropertyUtils.copyProperties(usersBizBean, usersInfo);
				}
				usersList.add(usersBizBean);
			}
		}
		
		return usersList;
	}
	
	@Override
	public RoleBizBean getRoleByName(String roleName) {
		RoleInfo roleInfo = this.roleDao.getRoleByName(roleName);
		RoleBizBean roleBizBean = null;
		if(null != roleInfo){
			roleBizBean = new RoleBizBean();
			PropertyUtils.copyProperties(roleBizBean, roleInfo);
		}
		return roleBizBean;
	}
	
	@Override
	public Map<String, List<AuthorityBizBean>> getRoleAuth(Long roleId) {
		RoleInfo role = roleDao.getEntityById(RoleInfo.class, roleId);
		return getPoToVo(role.getAuthoritySet());
	}
	/**
	 * PO 转换   VO
	 * @param authoritySet
	 * @return
	 */
	private Map<String, List<AuthorityBizBean>> getPoToVo(Set<AuthorityInfo> authoritySet) {
		AuthorityInfo[] auths = authoritySet.toArray(new AuthorityInfo[0]);
		List<AuthorityBizBean> authList = getAuthALL();
		List<AuthorityBizBean> auth_List = getCopy(Arrays.asList(auths));
		for (Iterator<AuthorityBizBean> iterator = auth_List.iterator(); iterator.hasNext();) {
			AuthorityBizBean authBussiness = iterator.next();
			for (Iterator<AuthorityBizBean> iterator2 = authList.iterator(); iterator2.hasNext();) {
				AuthorityBizBean authBussiness1 =iterator2.next();
				// 从所有权限中移除已关联权限
				if (authBussiness.getId().intValue()==authBussiness1.getId().intValue()) {
					authList.remove(authBussiness1);
					break;
				}
			}
		}
		Map<String, List<AuthorityBizBean>> temp_Map = new HashMap<String, List<AuthorityBizBean>>();
		temp_Map.put("auth_y", auth_List); // 已经关联菜单
		temp_Map.put("auth_n", authList); // 没有关联菜单
		return temp_Map;
	}
	/**
	 * 获得所有权限
	 * @return
	 */
	private List<AuthorityBizBean> getAuthALL() {
		List<AuthorityInfo> authInfoList = authDao.getAuthList(null,null);
		return getCopy(authInfoList);
	}
	/**
	 * 权限po 转换   vo
	 * @param authInfoList
	 * @return
	 */
	private List<AuthorityBizBean> getCopy(List<AuthorityInfo> authInfoList) {
		List<AuthorityBizBean> authb_list = new ArrayList<AuthorityBizBean>();
		for (Iterator<AuthorityInfo> iterator = authInfoList.iterator(); iterator.hasNext();) {
			AuthorityInfo authPO = iterator.next();
			AuthorityBizBean authVO = new AuthorityBizBean();
			BeanUtils.copyProperties(authPO, authVO);
			authb_list.add(authVO);
		}
		return authb_list;
	}
	
	public AuthDao getAuthDao() {
		return authDao;
	}
	@Resource
	public void setAuthDao(AuthDao authDao) {
		this.authDao = authDao;
	}
	
	@Override
	public List<ResourseBizBean> getRoleResourse(Long roleId) {
		
		if(null != roleId){
			List<ResourseInfo> resourseInfoList = roleDao.getRoleResourse(roleId);
			List<ResourseBizBean> resourseBizBeanList = new ArrayList<ResourseBizBean>();
			
			if(null != resourseInfoList && resourseInfoList.size()> 0){
				for (ResourseInfo po : resourseInfoList) {
					if(po.getMarkDelete().equals("N")){
						ResourseBizBean vo = new ResourseBizBean();
						PropertyUtils.copyProperties(vo, po);
						if(null != po && po.getParentResourseInfo() == null){
							// 子节点
							if(null != po.getChildrenList() && po.getChildrenList().size() > 0 && po.getMarkDelete().equals("N")){
								ResourseBizBean vo1 = getVotoPo(po);
								if(null != vo1){
									vo = vo1;
								}
							}
						}
						resourseBizBeanList.add(vo);
					}
				}
			}
			return resourseBizBeanList;
		}
		return null;
	}
	
	private ResourseBizBean getVotoPo(ResourseInfo po){
		ResourseBizBean tempVo = new ResourseBizBean();
		PropertyUtils.copyProperties(tempVo, po);
		if(po.getChildrenList().size() > 0 && po.getChildrenList() !=null){
			List<ResourseBizBean> temp = new ArrayList<ResourseBizBean>();
			for (ResourseInfo po1 : po.getChildrenList()) {
				if(po1.getMarkDelete().equals("N")){
					ResourseBizBean vo = new ResourseBizBean();
					PropertyUtils.copyProperties(vo, po1);
					
					if(null != po1 && null != po1.getChildrenList() && po1.getChildrenList().size() > 0){
						vo = getVotoPo(po1);
					}
					vo.setParentResourseBizBean(tempVo);
					temp.add(vo);
				}
			}
			tempVo.setChildrenList(temp);
		}
		return tempVo;
	}
	@Override
	public List<ResourseBizBean> getNotRoleResourse(Long roleId) {
		
		if(null != roleId){
			List<ResourseInfo> resourseInfoList = roleDao.getNotRoleResourse(roleId);
			List<ResourseBizBean> resourseBizBeanList = new ArrayList<ResourseBizBean>();
			
			if(null != resourseInfoList && resourseInfoList.size()> 0){
				for (ResourseInfo po : resourseInfoList) {
					if(po.getMarkDelete().equals("N")){
						ResourseBizBean vo = new ResourseBizBean();
						PropertyUtils.copyProperties(vo, po);
						if(null != po && po.getParentResourseInfo() == null){
							// 子节点
							if(null != po.getChildrenList() && po.getChildrenList().size() > 0 && po.getMarkDelete().equals("N")){
								ResourseBizBean vo1 = getVotoPo(po);
								if(null != vo1){
									vo = vo1;
								}
							}
						}
						resourseBizBeanList.add(vo);
					}
				}
			}
			return resourseBizBeanList;
		}
		return null;
	}
	
	@Override
	public List<RoleBizBean> getUserRoles(Integer userId, QueryPage queryPage) {
		if(null != userId){
			List<RoleBizBean> roleBizBeanList = new ArrayList<RoleBizBean>();
			List<RoleInfo> roleInfoList = roleDao.getUserRoles(userId, queryPage);
			
			if(null != roleInfoList && roleInfoList.size() > 0){
				for (RoleInfo roleInfo : roleInfoList) {
					RoleBizBean roleBizBean = new RoleBizBean();
					PropertyUtils.copyProperties(roleBizBean, roleInfo);
					roleBizBeanList.add(roleBizBean);
				}
			}
			return roleBizBeanList;
			
		}
		return null;
	}
	@Override
	public RoleBizBean getModel(RoleBizBean vo) {
		RoleInfo roleInfo = roleDao.getModel(vo);
		if(null != roleInfo){
			RoleBizBean roleBizBean = new RoleBizBean();
			PropertyUtils.copyProperties(roleBizBean, roleInfo);
			// 权限
			if(null != roleInfo.getAuthoritySet() && roleInfo.getAuthoritySet().size() > 0){
				Set<AuthorityBizBean> authVOSet = getCopyAuth(roleInfo.getAuthoritySet());
				roleBizBean.setAuthoritySet(authVOSet);
			}
			// 用户
			if(null != roleInfo.getUserSet() && roleInfo.getUserSet().size() > 0){
				Set<UsersBizBean> usersVOSet = getCopyUsers(roleInfo.getUserSet());
				roleBizBean.setUserSet(usersVOSet);
			}
			return roleBizBean;
		}
		return null;
	}
	@Override
	public List<ResourseBizBean> getRoleResourse(List<Long> ids) {
		if(null != ids && ids.size() > 0){
			// 
			String roleIds = StringUtils.getStringByCommaLong(ids);
			List<ResourseInfo> resourseInfoList = roleDao.getRoleResourse(roleIds);
			List<ResourseBizBean> resourseBizBeanList = new ArrayList<ResourseBizBean>();
			
			if(null != resourseInfoList && resourseInfoList.size()> 0){
				for (ResourseInfo po : resourseInfoList) {
					if(po.getMarkDelete().equals("N")){
						ResourseBizBean vo = new ResourseBizBean();
						PropertyUtils.copyProperties(vo, po);
						if(null != po && po.getParentResourseInfo() == null){
							// 子节点
							if(null != po.getChildrenList() && po.getChildrenList().size() > 0 && po.getMarkDelete().equals("N")){
								ResourseBizBean vo1 = getVotoPo(po);
								if(null != vo1){
									vo = vo1;
								}
							}
						}
						resourseBizBeanList.add(vo);
					}
				}
			}
			return resourseBizBeanList;
		}
		return null;
	}
}
